package com.sso.oa.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.sso.common.cons.Const;
import org.sso.common.cons.ParamConst;
import org.sso.common.cookie.CookieHelper;
import org.sso.common.cookie.TokenHelper;
import org.sso.common.domian.Ticket;
import org.sso.common.domian.Token;
import org.sso.common.util.HttpUtil;

import com.sso.oa.cons.OaConst;

/**
 * 跨域sso
 * 
 * @author spjich
 *
 */
public class CrossInterceptor extends HandlerInterceptorAdapter {
	private static final Logger logger = LoggerFactory.getLogger(CrossInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println(request.getRequestURI());
		Token token = TokenHelper.getToken(request);
		if (token == null) {
			// 用oa系统私钥生成签名
			Ticket tic = new Ticket(request, OaConst.RSA_OA_PRIVATE_KEY);
			CookieHelper.addCookie(request, response, OaConst.ticket_domian, Const.cookie_path, Const.ticket_cookiename,
					tic, Const.COOKIE_MAX_AGE, true, false);
			String redurl = HttpUtil.encodeRetURL(ParamConst.crossUrl, Const.ReturnURL, OaConst.cross_callback);
			response.sendRedirect(redurl + "&data=" + tic.encryptToken());
			logger.info("token为空，重定向到sso登录页面...|" + redurl + "&data=" + tic.encryptToken());
			return false;
		}
		return true;
	}
}
